package com.hand.pp.filter;/**
 * @author Estelle@앙수청
 * @date 2019/7/17 9:55
 */

import com.hand.pp.connst.PerssionConstant;
import com.hand.pp.domain.User;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  @author Estelle@앙수청
 *  @date 2019/7/17 9:55
 */
/*@Component
@WebFilter(filterName = "perssionFilter", urlPatterns = "/")*/
@Order(101)
public class PerssionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("PerssionFilter init()");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest  httpServletRequest = (HttpServletRequest) servletRequest;
//        System.out.println("uri" + httpServletRequest.getRequestURI());
//        System.out.println("localAddr" + httpServletRequest.getLocalAddr());
//        System.out.println("remoteAddr" + httpServletRequest.getRemoteAddr());
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        boolean token = validateUserPerssion(httpServletRequest.getHeader("token"));
        if (token){
            filterChain.doFilter(servletRequest,servletResponse);
            httpServletResponse.setStatus(200);
        }else {
            httpServletResponse.setStatus(403);
        }
    }

    @Override
    public void destroy() {
        System.out.println("PerssionFilter destroy()");
    }

    private Boolean validateUserPerssion(String token){
        if (PerssionConstant.EXISTS_TOKEN.equals(token)){
            return true;
        }
        return false;
    }
}
